/**
 * create by zhangpu
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.bosc.marshall;

import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.api.util.Jsons;
import com.acooly.module.openapi.client.provider.bosc.BoscConstants;
import com.acooly.module.openapi.client.provider.bosc.domain.BoscNotify;
import com.acooly.module.safety.Safes;
import com.acooly.module.safety.signature.SignTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author zhangpu
 */
@Slf4j
@Component
public class BoscNotifyUnmarshall extends BoscMarshallSupport
        implements ApiUnmarshal<BoscNotify, Map<String, String>> {

    @Resource(name = "boscMessageFactory")
    private MessageFactory messageFactory;

    @SuppressWarnings("unchecked")
    @Override
    public BoscNotify unmarshal(Map<String, String> message, String serviceName) {
        try {
            log.info("通知报文{}", message);
            String signature = message.get(BoscConstants.SIGN);
            String plain = message.get(BoscConstants.RESP_DATA);
            Safes.getSigner(SignTypeEnum.Rsa.name()).verify(plain, getKeyPair(), signature);

            BoscNotify boscNotify = (BoscNotify) messageFactory.getNotify(serviceName);
            boscNotify = Jsons.parse(plain, boscNotify.getClass());
            boscNotify.setSign(signature);
            boscNotify.setService(serviceName);
            boscNotify.setResponseType(message.get(BoscConstants.RESPONSE_TYPE));
            boscNotify.setPartner(getProperties().getPlatformNo());
            return boscNotify;
        } catch (Exception e) {
            log.error("解析异步通知出错", e);
            throw new ApiClientException("异步通知 解析失败:" + e.getMessage());
        }

    }
}
